<template>
  <zsearch v-loading="loading">
      <template #title>
        <span>分院管理</span>
      </template>
      <template #btns>
        <!-- <el-button class="btn-1" @click="hanledSearch">查询</el-button> -->
        <el-button class="btn-1" @click="refresh">刷新</el-button>
        
      </template>
      <template #opration>
        <el-button class="btn-2" @click="addRole">添加分院</el-button>
      </template>
      <template #table>
        <el-table :data="data" style="width: 100%" border>
          <el-table-column prop="name" label="名称" width="180" />
          <el-table-column prop="phone" label="电话" width="180" />
          <el-table-column prop="address" label="地址" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button text size="small" @click="handleEdit(scope.row)">修改</el-button>
              <el-button text size="small" @click="handleDetele(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #page>
      </template>
    </zsearch>

    <!-- 添加/修改 -->
    <zdialog :title="roleTitle" @handleClose="closeDialog" v-model="dialogVisible" :btnData="dialogBtnData">
      <template #body>
        <div>
          <el-form :inline="true" :model="form" ref="ruleFormRef" label-width="80px" :rules="rules" class="demo-form-inline">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="电话">
              <el-input v-model="form.phone" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="地址">
              <el-input v-model="form.address" placeholder="请输入" />
            </el-form-item>
          </el-form>
        </div>
			</template>
    </zdialog>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, ref, onMounted } from 'vue'
import ztable from '@components/Table/index.vue'
import zpage from '@components/pagination/pagination.vue'
import zsearch from '@components/search/search.vue'
import zdialog from '@components/dialog/dialog.vue'

import useConfgin from './../../../hook/getconfig'

import useRequet, { RespData } from "./../../../hook/network"
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

import { getSubCompanyListApi, addSubCompanyApi, updateSubCompanyApi, delSubCompanyApi } from './../../../api/branch'

export default defineComponent({
  name: 'Branch',
  components: {
    ztable,
    zpage,
    zsearch,
    zdialog
  },
  setup() {
    const request = useRequet({ path: "" });
    let search = reactive({
      name: '',
      roleName: '',
      typeId: '',
      superDeptId: '',
      options: [],
      haveZeroCount: false,
      onlyHighPrice: false,
      onlyWarningCount: false,
      loading: false,

      current: 1,
      size: 10,
      total: 0,
    })
    const data = ref([])
    

    const form = reactive({
      name: '',
      phone: '',
      address: '',
    })
    const ruleFormRef = ref<FormInstance>()

    const rules = reactive<FormRules>({
      name: [
        { required: true, message: '名称不能为空哦', trigger: 'blur' },
      ],
    })
    
    //搜索
    const hanledSearch = () => {
      req()
    }
    const refresh = () => {
      req()
    }

    const handleType = () => {
      console.log('下拉')
    }

    // 修改分院
    const handleEdit = (rowData:any) => {
      let { id, superDeptId, roleName } = rowData;

          search.typeId = id
          search.superDeptId = superDeptId
          roleTitle.value = '修改分院'
          search.roleName = roleName
          dialogVisible.value = true
    }
    // 删除分院
    const handleDetele = (rowData: any) => {
      console.log(rowData)
      let { id } = rowData;
      ElMessageBox.confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async() => {
        let res:any = await delSubCompanyApi({}, id);
        if(res.code !== 0) return ElMessage.error(res.msg || '删除失败')
        ElMessage.success('删除成功')
        req()
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除',
        });
      })
    }


    const req = async() => {
      search.loading = true
      let res:any = await getSubCompanyListApi({});
      if(res.code !== 0) return ElMessage.error('获取分院列表' + res.msg)
      data.value = res.data

      search.loading = false
    }
    req()


    const closeDialog = () => {
      dialogVisible.value = false
    }

    const dialogVisible = ref(false)
    const roleTitle = ref('添加分院')

    const dialogBtnData = [
      {
        name: '取消',
				func: (data:object) => {
					console.debug('取消',JSON.parse(JSON.stringify(data)))
          dialogVisible.value = false
				}
      },
      {
        name: '保存',
        func: (data:object) => {
					console.debug('保存',JSON.parse(JSON.stringify(data)))

          let msg = '添加分院'
          let params = {
            name: form.name,
            phone: form.phone,
            address: form.address
          } as any
          if(search.typeId) {
            msg = '修改分院'
          }

          ruleFormRef.value?.validate(async(valid, fields) => {
            if (valid) {
              // // 添加
              if(search.typeId === '') {
                let res:any = await addSubCompanyApi(form);
                if(res.code !== 0) return ElMessage.error(msg + res.msg)
                  ElMessage.success(msg + res.msg)
                  closeDialog()
                  req()
              }

              // // 修改
              if(search.typeId) {
                params.id = search.typeId
                params.superDeptId = search.superDeptId
                let res:any = await updateSubCompanyApi(params)
                if(res.code !== 0) return ElMessage.error(msg + res.msg)
                ElMessage.success(msg + res.msg)
                closeDialog()
                req()
              }
              console.log('submit!')
            } else {
              console.log('error submit!', fields)
            }
          })
          
				}
      }
    ]

    // 添加分院
    const addRole = () => {
      roleTitle.value = '添加分院'
      search.typeId = ''
      search.superDeptId = ''
      dialogVisible.value = true
    }


    
    return { 
      data, 
      ...toRefs(search),
      hanledSearch,
      handleType,

      refresh,
      form,
      rules,
      ruleFormRef,
      handleEdit,
      handleDetele,


      request,

      dialogVisible,
      closeDialog,
      dialogBtnData,

      addRole,
      roleTitle,
    }
  }
})
</script>

<style lang="scss" scoped>

</style>